import type {ActionType} from '@ant-design/pro-components';
import {PageContainer, ProForm, ProFormSelect, ProFormText, ProList,} from '@ant-design/pro-components';
import '@umijs/max';
import {RightSquareOutlined, SearchOutlined} from '@ant-design/icons';
import {Button, Card, Input, Layout, Pagination, Space, Tag, Tooltip,Drawer} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import Sider from "antd/es/layout/Sider";
import {listProjectUsingPost} from "@/services/easyapi/eProject";
import {getMarketInterfaceInfoUsingPost} from "@/services/easyapi/eApiManage";
import {Helmet, history, useModel} from '@umijs/max';
import ApiMarketList from "@/pages/ApiMarket/components";
const ApiMarket: React.FC = () => {
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const actionRef = useRef<ActionType>();
  const [projectList, setProjectList] = useState<API.ProjectListVo[]>([]);
  const [projectName, setProjectName] = useState<string>('')
  const [apiMarketList, setApiMarketList] = useState<API.ApiMarketInfo[]>([])
  const [current, setCurrent] = useState<number>(1)
  const [projectId, setProjectId] = useState<number>(0)
  const [size, setSize] = useState<number>(10)
  const [apiNameCn, setApiNameCn] = useState<string>('')
  const [apiType, setApiType] = useState<number>(0);
  const [reqType, setReqType] = useState<number>(0)
  const [paramCfgType, setParamCfgType] = useState<number>(0)
  const[visible, setVisible] = useState<boolean>(false)

  useEffect(() => {
    fetchProjectList()
  }, []);
  useEffect(() => {
    fetchApiMarketInfo();
  }, [current, size, apiType, reqType, projectId, paramCfgType]); // 依赖这些状态，当它们改变时，重新调用 fetchApiMarketInfo

  const handleReset = async () => {
    // 先同步地重置状态
    setProjectId(0);
    setApiType(0);
    setApiNameCn('');
    setReqType(0);
    setParamCfgType(0);
    setCurrent(1);
    await fetchApiMarketInfo();
  };


  const fetchApiMarketInfo = async () => {
    const res = await getMarketInterfaceInfoUsingPost({
      current: current,
      size: size,
      apiNameCn: apiNameCn,
      apiType: apiType,
      reqType: reqType,
      projectId: projectId,
      paramCfgType: paramCfgType
    });
    if (res.code === 200) {
      setApiMarketList(res.data.records||[])
    } else {
      setApiMarketList([])
    }
  }

  const fetchProjectList = async () => {
    const res = await listProjectUsingPost({
      projectName: projectName
    })
    if (res.code === 200) {
      setProjectList(res.data||[])
    } else {
      setProjectList([])
    }
  }
// 定义列配置
  return (
    <Layout style={{height: '100vh'}}>
      <div
        style={{
          position: 'fixed',
          top: '50%',
          left: visible ? '220px' : '0',
          transform: 'translateY(-50%)',
          backgroundColor: 'rgba(0,0,0,0.5)',
          padding: '8px',
          cursor: 'pointer',
          zIndex: 1000, // 确保按钮显示在其他组件之上
          borderRadius: '0 4px 4px 0',
        }}
        onClick={() => setVisible(!visible)}
      >
        <>
          <Tooltip style={{color: 'red'}} title={"点击展开项目列表"}>
            <RightSquareOutlined style={{color: '#d11111', fontSize: '20px'}}/>
          </Tooltip>
        </>
      </div>
      <Drawer
        title="项目列表"
        placement="left"
        width={220}
        onClose={() => setVisible(false)}
        visible={visible}
        bodyStyle={{
          padding: '1px',
          backgroundColor: 'rgba(0,0,0,0.94)',
        }}
        mask={false} // 关闭遮罩
      >
      <Sider
        width={220}
        style={{
          backgroundColor: '#000000',
          borderRight: '1px solid #f0f0f0',
          padding: '1px',
          overflow: 'auto', // Add overflow here to enable scrolling
          height: '100%' // Ensures the Sider takes up the full viewport height
        }}
      >

        <Input.Search
          placeholder="搜索项目"
          value={projectName}
          onChange={(e) => setProjectName(e.target.value)}
          style={{marginBottom: '16px'}}
          onSearch={() => {
            fetchProjectList()
          }}
          enterButton={true}
        />
        <ProList<API.ProjectListVo>
          actionRef={actionRef}
          rowKey="id"
          dataSource={projectList}
          showActions="hover"
          editable={{
            onSave: async (key, record, originRow) => {
              console.log(key, record, originRow);
              return true;
            },
          }}
          onItem={(item, index) => {
            return {
              onClick: () => {
                setProjectId(item.id)
                actionRef.current?.reload()
              },
            }
          }}
          onDataSourceChange={setProjectList}
          metas={{
            title: {
              dataIndex: 'projectName',
            },
            description: {
              dataIndex: 'projectDesc',
              render: (desc) => {
                return (
                  <div
                    style={{
                      maxWidth: '200px', // 限制最大宽度
                      whiteSpace: 'nowrap', // 禁止换行
                      overflow: 'hidden', // 隐藏超出部分
                      textOverflow: 'ellipsis', // 添加省略号
                    }}
                  >{desc}</div>
                )
              }
            },
            subTitle: {
              render: () => {
                return (
                  <Space size={0}>
                    <Tag color="#5BD8A6">EasyApi</Tag>
                  </Space>
                );
              },
            },
          }}
        />
      </Sider>
      </Drawer>

      {/* 旁边的组件 */}
      <div
        style={{
          flex: 1,
          marginLeft: visible ? '220px' : '0', // 根据抽屉状态调整边距
          transition: 'margin-left 0.3s ease', // 添加过渡动画
        }}
      >
      <Layout style={{padding: '2px', backgroundColor: '#000000'}}>
        <PageContainer>
          <ProForm.Group style={{marginBottom: '16px', display: 'flex', justifyContent: 'space-between'}}>
            <ProFormSelect
              width={"sm"}
              label={"请求类型"}
              tooltip={"生成api的请求类型"}
              name={'reqType'}
              valueEnum={{
                0: "GET",
                1: "POST"
              }}
              onChange={(value, option) => {
                setReqType(option.key)
              }}
            />
            <ProFormSelect
              width={"sm"}
              label={"参数配置模式"}
              tooltip={"生成api的参数配置模式"}
              name={"paramCfgType"}
              valueEnum={{
                0: "向导模式",
                1: "sql模式"
              }}
              onChange={(value, option) => {
                setParamCfgType(option.key)
              }}
            />
            <ProFormSelect
              width={"sm"}
              label={"api类型"}
              tooltip={"生成|注册"}
              name={"apiType"}
              valueEnum={{
                0: "生成",
                1: "注册"
              }}
              onChange={(value, option) => {
                console.log("apiType", option.key)
                setApiType(option.key)
              }}
            />
            <ProFormText
              width={'md'}
              name="apiNameCn"
              label={"api名称"}
              onChange={(value) => {
                setApiNameCn(value.target.value)
                console.log("apiNameCn", value.target.value)
              }}
              tooltip={"api中文名称1-255字符"}
              placeholder={'api名称'}
              rules={[
                {max: 255, message: 'api名称过长'}
              ]}
            />
            <Button
              shape="circle"
              type="default"
              onClick={() => {
                // Handle unified search logic here
                fetchApiMarketInfo()
              }}
              icon={<SearchOutlined/>}
            >
            </Button>
            <Button
              type="default"
              onClick={() => {
                // Handle unified search logic here
                handleReset()
              }}
            >
              重置
            </Button>
          </ProForm.Group>
          <ApiMarketList visible={visible} apiMarketInfo={apiMarketList}/>
          <Space
            direction="horizontal"
            style={{marginTop: '16px', justifyContent: 'center'}}
          >
            <Pagination
              style={{textAlign: 'center'}}
              defaultCurrent={current}
              current={current}
              //@ts-ignore
              pagesize={size}
              defaultPageSize={10}
              hideOnSinglePage={true}
              showQuickJumper={true}
              total={apiMarketList == null ? 0 : apiMarketList.length} //apiMarketList==null?0:apiMarketList.length
              onChange={(page, size) => {
                // Handle pagination change here
                setCurrent(page)
                setSize(size)
                console.log(`Page: ${page},size:${size}`);
                // Fetch data with the selected page and pageSize
              }}
            />
          </Space>
        </PageContainer>
      </Layout>
      </div>
    </Layout>
  );
};
export default ApiMarket;
